package gen.tools;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UpdateDeltaskStatus extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UpdateDeltaskStatus() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		final int deliverySN = Integer.parseInt( request.getParameter("deliverySN") );			//交付事件代碼
		final int tarDeliverySN = Integer.parseInt( request.getParameter("tarDeliverySN") );	//交付方的交付事件代碼
		final int targetSystemId =  Integer.parseInt( request.getParameter("targetSystemId") );
		int statusSN =  Integer.parseInt( request.getParameter("statusSN") );	//狀態碼
		String empId = request.getParameter("empId");
		String resultText = "OK";
		
		try {
			final int localSysemId = wid.getLocalSysemId();

			if ( statusSN == 6) {	//已提領待送審
				boolean isDepApplyNeed = Boolean.parseBoolean( wid.getSysParameter("isDepApplyNeed") );
				int dataType = 7; //審核可否部署
				int roleId = 8;	//CM主管	
				//empId 會是CM，他部署完後，由他的主管來審
				int toDoListId = wid.genToDoList("fOrder", String.valueOf(deliverySN), empId, dataType, roleId);
				statusSN = 7;	//已送審
				if( !isDepApplyNeed ) {	//不需審核可否部署
					//因為不需要確認結果 所以系統直接產生同意的記錄
					wid.completedList(toDoListId, wid.SYSID);
					statusSN = 9;	//待部署
				}
			} else if( statusSN == 11) {	//已部署待確認
				
				final boolean isTestNeedConfirm = Boolean.parseBoolean( wid.getSysParameter("isTestNeedConfirm") );	
				//先產生一筆待確認的記錄
				int dataType = 8; //確認部署結果
				int roleId = 8;	//CM主管	
				//empId 會是CM，他部署完後，由他的主管來審
				int toDoListId = wid.genToDoList("fOrder", String.valueOf(deliverySN) , empId, dataType, roleId);
				
				if( !isTestNeedConfirm ) {	//不需確認結果
					//因為不需要確認結果 所以系統直接產生同意的記錄
					wid.completedList(toDoListId, wid.SYSID);
					statusSN = 12;	//已確認成功
				}
			} 
			
			//修改交付事件的狀態ID
			wid.updateDeltaskStatus(deliverySN, statusSN, wid.getConn() );
			wid.updateDeltaskStatus(tarDeliverySN, statusSN, wid.getTarConnection(request, targetSystemId) );
			
		} catch(Exception e) {
			resultText = wid.errLog(e);
		}
		
		response.getWriter().write(resultText);
	}
}
